/**下载、打包、启动  平台工具类 */
const fs = require('fs');
const path = require("path");
const chalk = require("chalk");
const process = require('child_process');
const iconv = require('iconv-lite')

/**环境配置文件地址 */
const envconffile = "env.conf.js";
/**sql 文件地址 */
const mysqlpath = "env/hotdog/hotdog.sql";

/**
 * 导入mysql环境
 */
function importMysql(){
	return new Promise(async function (resolve,reject){
		try{
			let envconf = require(path.resolve("./",envconffile));
			let importOrder = "mysql -u"+envconf.dbuser+" -p"+envconf.dbpassword+" -h"+envconf.dbconnection+" -P"
			+envconf.dbport+" "+envconf.dbdatabase+"<"+path.resolve("./",mysqlpath);
			console.log(chalk.yellow("[hotdog debug]执行导入数据表指令："+importOrder));
			await execCommandByPath(importOrder , {message:'导入mysql数据表',cwd:envconf.mysqlbinpath,encoding:'GBK'});
			resolve();
		}catch(err){
			reject(err);
		}
	});
}

/**
 * 执行带路径的工具函数
 */
function execCommandByPath(command, data){
	return new Promise(function(resolve,reject){
		process.exec(command,data, function(error, stdout, stderr) {
			console.log(chalk.yellow("[hotdog debug]执行指令的路径："+data.cwd));
			if (error) {
                console.log(chalk.red(data.message+' 失败'));
				console.log(chalk.red(error));
                reject(error);
            } else if (stderr.lenght > 0) {
                reject(new Error(stderr.toString()));
            } else {
                console.log(chalk.yellow(data.message+' 成功'));
                resolve();
            }
		});
	});
}


exports.importMysql = importMysql;